const path = require('path');
const { merge } = require('webpack-merge');
const nodeExternals = require('webpack-node-externals');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const common = require('./webpack.common.js');
const removeCssImports = require('./babel-remove-css-imports');

module.exports = merge(common, {
  mode: 'development',
  target: 'node',
  entry: './src/server/index.ts',
  resolve: {
    modules: ['src/server', 'src/shared', 'node_modules'],
    extensions: ['.tsx', '.ts', '.js'],
    plugins: [
      new TsconfigPathsPlugin({
        configFile: path.resolve(__dirname, 'tsconfig.server.json')
      })
    ]
  },
  output: {
    filename: 'server.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        include: path.resolve(__dirname, 'src'),
        exclude: [/node_modules/, path.resolve(__dirname, 'src/client')],
        use: [
          {
            loader: 'babel-loader',
            options: {
              plugins: [removeCssImports],
              cacheDirectory: true,
              cacheCompression: false,
              cacheIdentifier: 'server',
              presets: [
               '@babel/preset-env',
                '@babel/preset-react',
                ['@babel/preset-typescript', { isTSX: true, allExtensions: true }]
              ]
            }
          },
          {
            loader: 'ts-loader',
            options: {
              configFile: 'tsconfig.server.json',
              transpileOnly: true,
              onlyCompileBundledFiles: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new ForkTsCheckerWebpackPlugin({
      typescript: {
        configFile: 'tsconfig.server.json'
      }
    }),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'src/server/template.ejs'),
          to: path.resolve(__dirname, 'dist')
        }
      ]
    })
  ],
  externals: [nodeExternals()]
}); 
